package com.tencent.qcloud.tim.uikit.modules.group.member

import android.content.Context
import android.content.Intent
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import com.lxj.xpopup.XPopup
import com.manor.common.Constants
import com.manor.common.activity.AbsActivity
import com.manor.common.http.HttpCallback
import com.manor.common.ktx.setBindViewPager
import com.manor.common.ktx.toBeanList
import com.manor.common.utils.KLog
import com.manor.common.utils.StringUtil
import com.manor.common.utils.ToastUtil
import com.tencent.qcloud.tim.uikit.R
import com.tencent.qcloud.tim.uikit.bean.*
import com.tencent.qcloud.tim.uikit.http.TkHttpConst
import com.tencent.qcloud.tim.uikit.http.TkHttpUtil
import com.tencent.qcloud.tim.uikit.http.TkHttpUtil.cancel
import kotlinx.android.synthetic.main.activity_invite_group.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 *

 *
 * @date  2020/8/17  14:37
 * @version 1.0
 */
public class InviteHGroupActivity : AbsActivity() {
    private lateinit var mAdapter: FriendInviteAdapter
    private val titleList = listOf("  邀请互粉好友  ", "邀请分享好友")
    private var groupId = ""

    companion object {
        fun forward(context: Context, id: String) {
            Intent(context, InviteHGroupActivity::class.java).apply {
                this.putExtras(bundleOf(Constants.GROUP_ID to id))
                context.startActivity(this)
            }
        }
    }


    override fun getLayoutId(): Int = R.layout.activity_invite_group


    override fun main() {
        groupId = intent?.extras?.getString(Constants.GROUP_ID) ?: groupId
        if (StringUtil.isEmpty(groupId)) {
            ToastUtil.show("数据异常")
            finish()
            return
        }

        InviteLiveData.clearAll()
        val fragmentList: MutableList<Fragment> = mutableListOf(
                InviteHFansFragment.newInstance(),
                InviteShareHFragment.newInstance()
        )
        mViewPager.offscreenPageLimit = 2
        mAdapter = FriendInviteAdapter(this, fragmentList)
        mViewPager.adapter = mAdapter
        tabLayout.setBindViewPager(mViewPager, titleList)
        ivBack.setOnClickListener { finish() }
        tvConfirm.setOnClickListener { goConfirm() }
        tvSelectNum.text = "已选0"
        doNet()
        EventBus.getDefault().register(this)
    }


    override fun onDestroy() {
        cancel(TkHttpConst.GET_FILTER_FRIEND)
        cancel(TkHttpConst.INVITE_FRIEND)
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }


    private fun goConfirm() {
        val fansIds = InviteLiveData.getCheckIds(FRIEND_TYPE_FANS)
        val shareIds = InviteLiveData.getCheckIds(FRIEND_TYPE_SHARE)
        val curCheckNUm = InviteLiveData.getCheckNum(FRIEND_TYPE_FANS) + InviteLiveData.getCheckNum(FRIEND_TYPE_SHARE)

        if (curCheckNUm <= 0 || (fansIds.isEmpty() && shareIds.isEmpty())) {
            ToastUtil.show("至少选中一个好友")
            return
        }
        val popup = XPopup.Builder(this@InviteHGroupActivity)
                .asLoading("")

        popup?.show()

        val toId = if (StringUtil.isNotEmpty(fansIds)) {
            if (StringUtil.isNotEmpty(shareIds))
                "$fansIds,$shareIds"
            else
                fansIds
        } else {
            shareIds
        }
        TkHttpUtil.getInviteFriend(groupId, toId, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String?, info: String?) {
                popup?.dismiss()
                if (code == 0) {
                    ToastUtil.show("邀请成功")
                    EventBus.getDefault().post(GroupInfoUpdate())
                    finish()
                } else {
                    msg?.let { ToastUtil.show(it) }
                }
            }

            override fun onError() {
                super.onError()
                popup?.dismiss()
            }

        })


//        ImHttpUtil.createChatGroup(name = etName.str(), title = etContent.str(), hfIds = fansIds, ztIds = shareIds,
//                callback = object : HttpCallback() {
//                    override fun onSuccess(code: Int, msg: String?, info: String?) {
//                        popup?.dismiss()
//                        if (code == 0) {
//                            Handler().postDelayed({
//                                ToastUtil.show("您已成功创建群聊！")
//                                finish()
//                            }, 200
//                            )
//                        } else {
//                            msg?.let { ToastUtil.show(it) }
//                        }
//                    }
//
//                    override fun onError() {
//                        super.onError()
//                        popup?.dismiss()
//                    }
//
//                })
    }


    private fun doNet() {
        val popup = XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .asLoading("正在加载数据")

        popup?.show()
        val curTime = System.currentTimeMillis()
        TkHttpUtil.getFilterFriend(groupId, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String?, info: String?) {
                popup?.dismiss()
                if (code == 0) {
                    if (info != null && info.isNotEmpty()) {
                        val list = info.toBeanList<MsgFriendBean>()
                        val hs = System.currentTimeMillis() - curTime
                        KLog.e("InviteLiveData-observer", "接口请求 time = $hs")
                        if (list.size > 0 && InviteLiveData.friendList.value?.size ?: 0 != list.size) {
                            InviteLiveData.addData(list)
                            InviteLiveData.changeEditStatus(true)
                            InviteLiveData.initSplitData()
                        }
                    }
                }
            }

            override fun onError() {
                super.onError()
                popup?.dismiss()
            }
        })
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGroupChange(e: GroupHChange) {
        val num = InviteLiveData.getCheckNum(FRIEND_TYPE_FANS) + InviteLiveData.getCheckNum(FRIEND_TYPE_SHARE)
        tvSelectNum.text = "已选$num"
        tvConfirm.isSelected = num > 0
        KLog.e("CreateGroupActivity", "fansIds = ${InviteLiveData.getCheckNum(FRIEND_TYPE_FANS)} , shareIds = ${InviteLiveData.getCheckNum(FRIEND_TYPE_SHARE)}")
    }

}